package main

import (
	"errors"
	"fmt"
	"math/rand"
	"runtime"
	"sync"
)

const (
	Normal   = 0
	UnNormal = 1
)

type conn struct {
	Id    int
	Addr  string
	State int
}

type connPool struct {
	sync.Pool
}

func (p *connPool) get() (*conn, error) {
	con := p.Pool.Get().(*conn)
	if con.State == UnNormal {
		return nil, errors.New("节点不可用")
	}
	if con == nil {
		fmt.Println("新增节点。。。。。")
	}
	return con, nil
}
func (p *connPool) put(con *conn) {
	p.Pool.Put(con)
}
func NewConnPool(addr string) *connPool {
	return &connPool{
		Pool: sync.Pool{
			New: func() any {

				randId := rand.Intn(10)
				fmt.Println("randId=", randId)
				return &conn{
					Id:    randId,
					Addr:  addr,
					State: 0,
				}
			},
		},
	}
}
func main() {
	fmt.Println(runtime.NumCPU(), runtime.GOMAXPROCS(0))
	p := NewConnPool("192.168.2.1")
	var wg sync.WaitGroup
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			con, err := p.get()

			fmt.Println(con, err)
			p.put(con)
		}()
	}
	wg.Wait()
	fmt.Println("main....")
}
